<template>
	<view class="container">
		<!-- 顶部统计卡片 -->
		<view class="stats-header f f-a-c f-j-b">

			<view class="left">
				<view style="padding-bottom: 10rpx;" class="f ">
					<view class="text">
						人数：{{ reportData.students ? reportData.students.length : 0 }}
					</view>
					<view class="text">
						未提交学生
					</view>
				</view>
				<view style="padding-bottom: 10rpx;" class="f ">
					<view class="text">
						提交：{{ reportData.submitNum }}
					</view>
				</view>
				<view style="padding-bottom: 10rpx;" class="f ">
					<view class="text">
						AI批改：{{ reportData.checkNum }}
					</view>

				</view>
				<view style="padding-bottom: 10rpx;" class="f ">
					<view class="text">
						异常：{{ reportData.exceptNum }}
					</view>
				</view>
				<!-- <view style="padding-bottom: 10rpx;" class="f ">
					<view class="text">
						未审阅：2
					</view>

				</view> -->
			</view>
			<view class="right f f-a-c f-d-c f-j-b">
				<view style="background: #00CCA3;" class="btnT f f-a-c f-j-c">
					90分以上：{{ scoreStatistics.scoreNinetyPlus }}
				</view>
				<view style="background: #F13E2E;" class="btnT f f-a-c f-j-c">
					0-90分：{{ scoreStatistics.scoreZeroToNinety }}
				</view>
				<view style="background: #AEAEAE;" class="btnT f f-a-c f-j-c">
					未批改：{{ scoreStatistics.ungraded }}
				</view>
			</view>
		</view>

		<!-- 分数统计图表 -->
		<view class="chart-section">
			<view class="chart-header">
				<view class="chart-title-wrapper f f-a-c f-j-c">
					<view style="margin-top: -15rpx;" class="chart-title">分数统计</view>
				</view>
			</view>
			<view class="chart-container">
				<eachet :nameList="studentNameList" :list="studentScoreList"></eachet>
			</view>
		</view>

		<!-- AI建议 -->
		<view class="ai-suggestion">
			<view class=" f f-a-c">
				<view class="ai-header">
					<image src="/static/home/jianyi.png" class="ai-icon" mode="aspectFit"></image>
				</view>
				<view class="suggestion-content">
					<text class="suggestion-text">1. 建议重点训练"是、做"等字。</text>
					<text class="suggestion-text">2. 重点关注"小明"的学习情况，他的错误较多</text>
				</view>

			</view>
		</view>

		<!-- 作业展示区域 -->
		<view class="homework-sections">
			<!-- 异常作业 -->
			<view class="homework-section">
				<view class="section-header">
					<text class="section-title">异常作业 ({{ abnormalHomework.length }})</text>
				</view>
				<scroll-view class="homework-scroll" scroll-x="true">
					<view class="homework-list">
						<image src="/static/home/fen.png" class="fen" mode=""></image>
						<view v-if="abnormalHomework.length === 0" class="no-homework">
							<text class="no-homework-text">暂无异常作业</text>
						</view>
						<template v-else>
							<view v-for="(item, index) in abnormalHomework" :key="item.id" class="homework-item"
								@tap="viewHomework(item)">
								<image :src="item.thumbnail" class="homework-thumb" mode="aspectFill"
									@error="handleImageError" @load="handleImageLoad"></image>
								<view :class="{blue:index==1}" class="homework-badge error-badge f f-a-c f-j-c">
									{{ index == 1 ? '批阅' : '未批阅' }}
								</view>
							</view>
						</template>
					</view>
				</scroll-view>
			</view>

			<!-- 优秀作业 -->
			<view class="homework-section">
				<view class="section-header">
					<text class="section-title">优秀作业 ({{ excellentHomework.length }})</text>
				</view>
				<scroll-view class="homework-scroll" scroll-x="true">
					<view class="homework-list">
						<image src="/static/home/fen.png" class="fen" mode=""></image>
						<view v-if="excellentHomework.length === 0" class="no-homework">
							<text class="no-homework-text">暂无优秀作业</text>
						</view>
						<template v-else>
							<view v-for="(item, index) in excellentHomework" :key="item.id" class="homework-item"
								@tap="viewHomework(item)">
								<image :src="item.thumbnail" class="homework-thumb" mode="aspectFill"
									@error="handleImageError" @load="handleImageLoad"></image>
								<view class="homework-badges ">
									<image src="/static/home/1pai.png" v-if="index==0" class="imgSize" mode=""></image>
									<image src="/static/home/2pai.png" v-if="index==1" class="imgSize" mode=""></image>
									<image src="/static/home/3pai.png" v-if="index==2" class="imgSize" mode=""></image>
								</view>
							</view>
						</template>
					</view>
				</scroll-view>
			</view>

			<!-- 待提升作业 -->
			<view class="homework-section">
				<view class="section-header">
					<text class="section-title">待提升作业 ({{ improvementHomework.length }})</text>
				</view>
				<scroll-view class="homework-scroll" scroll-x="true">
					<view class="homework-list">
						<image src="/static/home/fen.png" class="fen" mode=""></image>
						<view v-if="improvementHomework.length === 0" class="no-homework">
							<text class="no-homework-text">暂无待提升作业</text>
						</view>
						<template v-else>
							<view v-for="(item, index) in improvementHomework" :key="item.id" class="homework-item"
								@tap="viewHomework(item)">
								<image :src="item.thumbnail" class="homework-thumb" mode="aspectFill"
									@error="handleImageError" @load="handleImageLoad"></image>
							</view>
						</template>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	import uCharts from "@qiun/ucharts";
	import eachet from "@/components/eachet.vue";
	export default {
		components: {
			eachet,
		},
		data() {
			return {
				// 学生分数统计数据（图表）
				studentScoreList: [], // 分数数组
				studentNameList: [], // 学生姓名数组

				// 原有的模拟数据（作为备用）
				list: [],
				nameList: [],

				// 接口返回的完整数据
				reportData: {},

				// 动态分数统计数据
				scoreStatistics: {
					scoreNinetyPlus: 0, // 90分以上人数
					scoreZeroToNinety: 0, // 0-90分人数
					ungraded: 0, // 未批改人数
				},

				statistics: {
					totalStudents: 20,
					friends: 19,
					trainings: 17,
					abnormal: 2,
					unreviewed: 2,
					unsubmittedStudent: "小红",
					allCorrect: 10,
					hasErrors: 7,
					ungraded: 2,
				},

				// 图表数据
				errorChartData: {
					categories: ["第1题", "第2题", "第3题", "第4题", "第5题"],
					series: [{
							name: "错误A",
							data: [15, 8, 12, 10, 16],
						},
						{
							name: "错误B",
							data: [20, 15, 18, 14, 20],
						},
						{
							name: "错误C",
							data: [12, 18, 15, 16, 12],
						},
						{
							name: "错误D",
							data: [8, 12, 10, 8, 14],
						},
					],
				},

				tutorChartData: {
					categories: ["第1题", "第2题", "第3题", "第4题", "第5题"],
					series: [{
							name: "辅导A",
							data: [15, 8, 12, 10, 16],
						},
						{
							name: "辅导B",
							data: [20, 15, 18, 14, 20],
						},
						{
							name: "辅导C",
							data: [12, 18, 15, 16, 12],
						},
						{
							name: "辅导D",
							data: [8, 12, 10, 8, 14],
						},
					],
				},

				// 作业数据
				abnormalHomework: [],
				excellentHomework: [],
				improvementHomework: [],
			};
		},

		onReady() {
			this.initErrorChart();
			this.initTutorChart();
		},
		onLoad(options) {
			this.init(options.taskId);
		},
		methods: {
			async init(id) {
				try {
					let n = await this.$api.compositionReport({
						taskId: id,
					});

					if (n.code == "0000" && n.data) {
						this.reportData = n.data;
						console.log("接口返回数据:", JSON.stringify(this.reportData));

						// 处理学生分数统计数据
						this.processStudentScoreData();

						// 处理作业图片数据
						await this.processHomeworkImages();

						// 更新统计信息
						this.updateStatistics();
					} else {
						console.error("获取报告数据失败:", n);
						this.setFallbackData();
					}
				} catch (error) {
					console.error("请求报告数据异常:", error);
					this.setFallbackData();
				}
			},

			/**
			 * 处理学生分数统计数据
			 */
			processStudentScoreData() {
				if (!this.reportData.students || this.reportData.students.length == 0) {
					console.log("没有学生数据，使用默认数据");
					this.studentNameList = ["默认学生"];
					this.studentScoreList = [0];
					return;
				}

				// 按分数降序排序，取前7个
				const sortedStudents = this.reportData.students
					.sort((a, b) => (b.score || 0) - (a.score || 0))
					.slice(0, 7);

				this.studentNameList = sortedStudents.map(
					(student) => student.studentName || "未知学生"
				);
				this.studentScoreList = sortedStudents.map(
					(student) => student.score || 0
				);

				console.log("学生分数统计数据处理完成:");
				console.log("学生姓名:", this.studentNameList);
				console.log("学生分数:", this.studentScoreList);

				// 计算分数统计
				this.calculateScoreStatistics();
			},

			/**
			 * 计算分数统计数据
			 */
			calculateScoreStatistics() {
				if (!this.reportData.students || this.reportData.students.length === 0) {
					console.log("没有学生数据，重置统计数据");
					this.scoreStatistics = {
						scoreNinetyPlus: 0,
						scoreZeroToNinety: 0,
						ungraded: 0,
					};
					return;
				}

				let scoreNinetyPlus = 0; // 90分以上
				let scoreZeroToNinety = 0; // 0-90分
				let ungraded = 0; // 未批改

				this.reportData.students.forEach((student) => {
					const score = student.score;

					// 判断是否有分数（已批改）
					if (score === null || score === undefined || score === "") {
						ungraded++;
					} else {
						const numScore = Number(score);
						if (numScore >= 90) {
							scoreNinetyPlus++;
						} else {
							scoreZeroToNinety++;
						}
					}
				});

				this.scoreStatistics = {
					scoreNinetyPlus,
					scoreZeroToNinety,
					ungraded,
				};

				console.log("分数统计计算完成:", this.scoreStatistics);
				console.log(
					`90分以上: ${scoreNinetyPlus}人, 0-90分: ${scoreZeroToNinety}人, 未批改: ${ungraded}人`
				);
			},

			/**
			 * 更新统计信息
			 */
			updateStatistics() {
				if (this.reportData) {
					this.statistics = {
						...this.statistics,
						totalStudents: this.reportData.classStuNum || 0,
						submitted: this.reportData.submitNum || 0,
						checked: this.reportData.checkNum || 0,
						abnormal: this.reportData.exceptNum || 0,
						scoreNinetyNum: this.reportData.scoreNinetyNum || 0,
						scoreZeroNineNum: this.reportData.scoreZeroNineNum || 0,
						averageScore: this.reportData.averageScore || 0,
					};
				}
			},

			/**
			 * 设置备用数据
			 */
			setFallbackData() {
				console.log("使用备用数据");
				this.studentNameList = ["学生A", "学生B", "学生C"];
				this.studentScoreList = [85, 78, 92];

				// 设置备用统计数据
				this.scoreStatistics = {
					scoreNinetyPlus: 1, // 学生C: 92分
					scoreZeroToNinety: 2, // 学生A: 85分, 学生B: 78分
					ungraded: 0,
				};
			},

			/**
			 * 处理作业图片数据
			 */
			async processHomeworkImages() {
				console.log("开始处理作业图片数据...");

				try {
					// 并行处理三种类型的作业图片
					const [abnormalHomework, excellentHomework, improvementHomework] =
					await Promise.all([
						this.fetchHomeworkImages(
							this.reportData.exceptHomeworks || [],
							"abnormal"
						),
						this.fetchHomeworkImages(
							this.reportData.excellentHomeworks || [],
							"excellent"
						),
						this.fetchHomeworkImages(
							this.reportData.needImproveHomeworks || [],
							"improvement"
						),
					]);

					this.abnormalHomework = abnormalHomework;
					this.excellentHomework = excellentHomework;
					this.improvementHomework = improvementHomework;

					console.log("作业图片处理完成:");
					console.log("异常作业:", this.abnormalHomework);
					console.log("优秀作业:", this.excellentHomework);
					console.log("需要提升作业:", this.improvementHomework);
				} catch (error) {
					console.error("处理作业图片失败:", error);
				}
			},

			/**
			 * 获取作业图片URLs
			 */
			async fetchHomeworkImages(imagePaths, type) {
				if (!imagePaths || imagePaths.length === 0) {
					console.log(`${type} 类型作业无图片数据`);
					return [];
				}

				const homeworkList = [];

				for (let i = 0; i < imagePaths.length; i++) {
					const imagePath = imagePaths[i];
					try {
						console.log(`正在获取 ${type} 作业图片 ${i + 1}:`, imagePath);

						const imageResponse = await this.$api.imageUrl({
							image: imagePath,
						});

						if (imageResponse.code === "0000" && imageResponse.data) {
							homeworkList.push({
								id: `${type}_${i + 1}`,
								thumbnail: imageResponse.data,
								imagePath: imagePath,
								type: type,
								index: i,
							});
							console.log(
								`${type} 作业图片 ${i + 1} 获取成功:`,
								imageResponse.data
							);
						} else {
							console.error(`${type} 作业图片 ${i + 1} 获取失败:`, imageResponse);
						}
					} catch (error) {
						console.error(`${type} 作业图片 ${i + 1} 请求异常:`, error);
					}
				}

				return homeworkList;
			},

			// 初始化错误统计图表
			initErrorChart() {
				this.list = [4, 5, 8, 10, 2, 5, 7];
				this.nameList = ["lzl", "lll", "llz", "zll", "zzl", "xz", "zx"];
				this.errorChart = new uCharts({
					type: "column",
					context: uni.createCanvasContext("errorChart", this),
					width: uni.upx2px(690),
					height: uni.upx2px(400),
					categories: this.errorChartData.categories,
					series: this.errorChartData.series,
					animation: true,
					background: "#FFFFFF",
					color: ["#5470C6", "#91CC75", "#FAC858", "#EE6666"],
					padding: [15, 15, 0, 5],
					enableScroll: false,
					legend: {
						show: false,
					},
					xAxis: {
						disableGrid: true,
						itemCount: 5,
						scrollShow: true,
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
						data: [{
							min: 0,
							max: 25,
						}, ],
					},
					extra: {
						column: {
							type: "group",
							width: uni.upx2px(20),
							activeBgColor: "#000000",
							activeBgOpacity: 0.08,
						},
					},
				});
			},

			// 初始化辅导统计图表
			initTutorChart() {
				this.tutorChart = new uCharts({
					type: "column",
					context: uni.createCanvasContext("tutorChart", this),
					width: uni.upx2px(690),
					height: uni.upx2px(400),
					categories: this.tutorChartData.categories,
					series: this.tutorChartData.series,
					animation: true,
					background: "#FFFFFF",
					color: ["#5470C6", "#91CC75", "#FAC858", "#EE6666"],
					padding: [15, 15, 0, 5],
					enableScroll: false,
					legend: {
						show: false,
					},
					xAxis: {
						disableGrid: true,
						itemCount: 5,
						scrollShow: true,
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
						data: [{
							min: 0,
							max: 25,
						}, ],
					},
					extra: {
						column: {
							type: "group",
							width: uni.upx2px(20),
							activeBgColor: "#000000",
							activeBgOpacity: 0.08,
						},
					},
				});
			},

			// 图表触摸事件
			touchErrorChart(e) {
				this.errorChart.showToolTip(e, {
					format: function(item, category) {
						return category + " " + item.name + ":" + item.data;
					},
				});
			},

			moveErrorChart(e) {
				this.errorChart.scroll(e);
			},

			touchEndErrorChart(e) {
				this.errorChart.hideToolTip();
			},

			touchTutorChart(e) {
				this.tutorChart.showToolTip(e, {
					format: function(item, category) {
						return category + " " + item.name + ":" + item.data;
					},
				});
			},

			moveTutorChart(e) {
				this.tutorChart.scroll(e);
			},

			touchEndTutorChart(e) {
				this.tutorChart.hideToolTip();
			},

			// 查看具体作业
			viewHomework(homework) {
				console.log("查看作业详情:", homework);

				// 预览图片
				uni.previewImage({
					urls: [homework.thumbnail],
					current: homework.thumbnail,
					success: () => {
						console.log("图片预览成功");
					},
					fail: (error) => {
						console.error("图片预览失败:", error);
						uni.showToast({
							title: "图片预览失败",
							icon: "error",
						});
					},
				});
			},

			handleImageError(e) {
				console.error("图片加载失败:", e);
				uni.showToast({
					title: "图片加载失败",
					icon: "error",
				});
			},

			handleImageLoad(e) {
				console.log("图片加载成功:", e);
			},
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background-color: #fff;
		padding: 30rpx;
	}

	.stats-header {
		height: 284rpx;
		// background-color: pink;
		margin-bottom: 30rpx;

		.left {
			width: 65%;
			height: 100%;
			background: #8bddf2;
			border-radius: 20rpx;
			padding: 20rpx;

			.text {
				width: 50%;
				font-family: SourceHanSansCN, SourceHanSansCN;
				font-weight: 500;
				font-size: 28rpx;
				color: #333333;
			}
		}

		.right {
			width: 30%;
			height: 100%;

			.btnT {
				width: 100%;
				font-family: SourceHanSansCN, SourceHanSansCN;
				font-weight: 500;
				font-size: 32rpx;
				color: #ffffff;
				height: 72rpx;
				border-radius: 10rpx;
			}
		}
	}

	.stats-row {
		display: flex;
		gap: 15rpx;
		margin-bottom: 15rpx;
	}

	.stat-card {
		flex: 1;
		background-color: #e8f4fd;
		padding: 20rpx;
		border-radius: 12rpx;
		text-align: center;

		&.special {
			background-color: #e8f4fd;
		}

		&.success {
			background-color: #28a745;
			color: white;
		}

		&.error {
			background-color: #dc3545;
			color: white;
		}

		&.pending {
			background-color: #6c757d;
			color: white;
		}
	}

	.stat-label {
		display: block;
		font-size: 24rpx;
		color: inherit;
		margin-bottom: 8rpx;
	}

	.stat-value {
		display: block;
		font-size: 28rpx;
		font-weight: bold;
		color: inherit;
	}

	.chart-section {
		background-color: white;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}

	.chart-header {
		margin-bottom: 20rpx;

		.chart-title-wrapper {
			width: 100%;
			height: 60rpx;

			.chart-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}

	.chart-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.chart-container {
		width: 100%;
		height: 400rpx;
	}

	.charts {
		width: 100%;
		height: 100%;
	}

	// AI建议模块
	.ai-suggestion {
		background-color: #fff3cd;
		border-radius: 12rpx;
		padding: 20rpx;
		margin: 0 30rpx 30rpx;
		border-left: 4rpx solid #ffc107;

		.ai-header {
			display: flex;
			align-items: center;
			margin-bottom: 15rpx;

			.ai-icon {
				width: 106rpx;
				height: 100rpx;
				margin-right: 10rpx;
			}

			.ai-title {
				font-size: 28rpx;
				font-weight: bold;
				color: #856404;
			}
		}

		.suggestion-content {
			padding-left: 20rpx;

			.suggestion-text {
				display: block;
				font-size: 26rpx;
				color: #856404;
				line-height: 1.5;
				margin-bottom: 8rpx;
			}
		}
	}

	// 作业展示模块
	.homework-sections {
		padding: 0 30rpx;
		margin-bottom: 40rpx;

		.homework-section {
			background-color: white;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.section-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				.section-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
			}

			.homework-scroll {
				width: 100%;

				.homework-list {
					position: relative;
					display: flex;
					gap: 20rpx;
					padding-bottom: 10rpx;

					.fen {
						position: absolute;
						width: 36rpx;
						height: 36rpx;
						bottom: 10rpx;
						right: 10rpx;
					}

					.homework-item {
						position: relative;
						width: 160rpx;
						height: 200rpx;
						border-radius: 12rpx;
						box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
						margin-right: 15rpx;
						margin-bottom: 20rpx;

						.homework-thumb {
							width: 100%;
							height: 100%;
							border-radius: 12rpx;
						}

						.homework-badge {
							position: absolute;
							top: 10rpx;
							right: 10rpx;
							width: 46rpx;
							height: 46rpx;
							border-radius: 23rpx;
							font-family: SourceHanSansCN, SourceHanSansCN;
							font-weight: 400;
							font-size: 12rpx;
							color: #FFFFFF;
							background: #F13E2E;
							display: flex;
							align-items: center;
							justify-content: center;

							&.blue {
								background-color: #4E95FF;
							}
						}

						.homework-badges {
							position: absolute;
							top: 0rpx;
							right: 0rpx;
							width: 54rpx;
							height: 59rpx;

							.imgSize {
								width: 100%;
								height: 100%;
							}
						}
					}

					.no-homework {
						display: flex;
						justify-content: center;
						align-items: center;
						height: 100%;

						.no-homework-text {
							font-size: 26rpx;
							color: #666;
						}
					}
				}
			}
		}
	}

	// 通用样式
	.f {
		display: flex;
	}

	.f-a-c {
		align-items: center;
	}

	.f-j-c {
		justify-content: center;
	}

	.f-j-b {
		justify-content: space-between;
	}

	.f-d-c {
		flex-direction: column;
	}

	.f-w {
		flex-wrap: wrap;
	}

	.f-1 {
		flex: 1;
	}

	.f-j-a {
		justify-content: space-around;
	}

	.f-a-s {
		align-items: flex-start;
	}

	.f-a-e {
		align-items: flex-end;
	}
</style>